﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using CygwinPackageManager.Properties;
using System.Diagnostics;

namespace CygwinPackageManager
{
	public static class Extensions
	{
		public static string ToFormattedList(this IList<string> strings)
		{
			return ToFormattedList(strings, string.Empty);
		}

		public static string ToFormattedList(this IList<string> strings, string footer)
		{
			string newLine = Environment.NewLine;
			string formattedList = string.Empty;

			if (strings.Count > 1)
			{
				foreach (string s in strings)
					formattedList += string.Concat(" - ", s, newLine);
			}
			else
			{
				formattedList += strings.FirstOrDefault();
			}

			if (!string.IsNullOrEmpty(footer))
				formattedList += string.Concat(newLine, footer);

			return formattedList;
		}

		public static void ShowProgress(this ContainerControl containerControl, string message)
		{
			ShowProgress(containerControl, message, false);
		}

		public static void ShowProgress(this ContainerControl containerControl, string message, bool showLog)
		{
			// TODO: Would be nice to have transparency but... Windows forms controls do not support true transparency and hacks to enable this feature have problems with underlying controls trying to repaint. Taking a screenshot of the form contents (http://www.developerfusion.com/code/4630/capture-a-screen-shot/) and blend the image is a possible solution but, if SetWorking is called in OnLoad, few controls will have been painted so the screenshot will be of an incomplete form.
			
			ProgressControl progressControl = containerControl.Controls
				.OfType<ProgressControl>()
				.FirstOrDefault();

			if (progressControl == null)
			{
				progressControl = new ProgressControl()
				{
					Dock = DockStyle.Fill,
					ShowLog = showLog,
					Message = message,
				};

				containerControl.SuspendLayout();
				containerControl.Controls.Add(progressControl);
				progressControl.BringToFront();
				containerControl.ResumeLayout();
			}
			else
			{
				progressControl.Message = message;
				progressControl.ShowLog = showLog;
			}
			
			foreach (ToolStrip toolStrip in containerControl.Controls.OfType<ToolStrip>())
				toolStrip.Visible = false;
		}

		public static void HideProgress(this ContainerControl containerControl)
		{
			foreach (ToolStrip toolStrip in containerControl.Controls.OfType<ToolStrip>())
				toolStrip.Visible = true;

			List<ProgressControl> progressControls = new List<ProgressControl>();
			foreach (ProgressControl progressControl in containerControl.Controls.OfType<ProgressControl>())
				progressControls.Add(progressControl);
			
			containerControl.SuspendLayout();
			foreach (ProgressControl progressControl in progressControls)
				containerControl.Controls.Remove(progressControl);
			containerControl.ResumeLayout();
		}
	}
}
